English 中文(简体)
我该怎么改写这个代码?
原标题:How should I rewrite this piece of code

这些函数 (*) 和 (**) 位于 < code> backbone.View 内, 但我认为不需要 Backbone 的知识来解决这个问题 。

As you can see from my comments in the code when:
1) I call the getAvatar function everything is ok,
2) when the getAvatar call the setAvatar something is broken

我应如何解决以下问题?


(*)

    getAvatar: function ()
    {
        var creatorIds = this.getCreatorIds();
        console.log(creatorIds); // [1,2]  ******  here is ok *******

        for (var c = 0, l = creatorIds.length; c < l; c += 1) {
            if (typeof this.avatars[creatorIds[c]] ===  undefined ) {
                this.userModel = new UserModel({id: creatorIds[c]});
                this.userModel.fetch();
                this.userModel.on( change , this.setAvatar, this);      
            }
        }
    },

(**)

    setAvatar: function ()
    {       
        console.log(this.userModel.get( id )); // 2, 2  *********  it should be 1, 2  *******
        this.names[this.userModel.get( id )] = this.userModel.get( name );
        this.avatars[this.userModel.get( id )] = typeof this.userModel.get( avatar );
        this.render();
    },

()

initialize: function ()
{
     _.bindAll(this,  getAvatar ,  setAvatar );
}
问题回答

似乎主干线 。 js 具有 < a href=> 的第三个上下文参数 。 http://documentcloud.github.com/backbone/ #Events-on' rel = “ nofollow' > on

object.on(event, callback, [context])

你的代码是

getAvatar: function ()
{
    var creatorIds = this.getCreatorIds();
    console.log(creatorIds); // [1,2]  ******  here is ok *******

    for (var c = 0, l = creatorIds.length; c < l; c += 1) {
        if (typeof this.avatars[creatorIds[c]] ===  undefined ) {
            this.userModel = new UserModel({id: creatorIds[c]});
            this.userModel.fetch();
            this.userModel.on( change , this.setAvatar, this );  //added this after the function.
        }
    }
},

或您可以使用关闭

getAvatar: function ()
{
    var that = this;  //variable to maintain scope
    var creatorIds = this.getCreatorIds();
    console.log(creatorIds); // [1,2]  ******  here is ok *******

    for (var c = 0, l = creatorIds.length; c < l; c += 1) {
        if (typeof this.avatars[creatorIds[c]] ===  undefined ) {
            this.userModel = new UserModel({id: creatorIds[c]});
            this.userModel.fetch();
            this.userModel.on( change , function(){ that.setAvatar(); } );  //use a closure here with that variable that which is defined above.    
        }
    }
},

问题在于您重新分配了两次相同的变量。 在 getAvatar () 中, 您将首先设置 this. user Model 给用户模式, 使用 id = = = = 1 。 然后在下一个循环迭代时, 它将被指定为 id = = 2 的用户模式 。

setAvatar () 函数被击中时, 它会查看 this. userModel 并只看到您设定的一个值。 您应该尽量不使用实例变量存储模型 。

这里有一种方法可以修复它。也许有比较容易的方法可以修复它,但从所提供的代码样本中很难看出。我还对代码中的一些奇特之处补充了几点评论。

(*)

getAvatar: function ()
{
    var creatorIds = this.getCreatorIds();
    console.log(creatorIds); // [1,2]  ******  here is ok *******

    var self = this;

    for (var c = 0, l = creatorIds.length; c < l; c += 1) {
        if (typeof this.avatars[creatorIds[c]] ===  undefined ) {
            var user = new UserModel({id: creatorIds[c]});

            //probably better to bind the handler first, in case fetch() completes synchronously from cache
            user.on( change , function(){
                console.log(user.get( id ));
                self.names[user.get( id )] = user.get( name );
                self.avatars[user.get( id )] = typeof user.get( avatar ); //are you sure you want typeof here?
                self.render(); //Note, this will get called a lot. Are you sure you want to do this?
            });   

            user.fetch();   
        }
    }
}




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.