Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - Trouble referencing variable in Collections.where method within render function

I have run into some trouble with a piece of backbone code. The code below relates to a render function. I can retrieve all the models. My trouble arises when I try to use the "Collections.where" method at line marked number #1. As you can see, I have passed an object literal into the render function but for some reason I am unable to reference it within the customers.where method on line #1. When I give this method a literal number like 45 it works. Is there some way around this so I can pass the variable reference in?

Thanks alot

render: function(options) {

    var that = this;
    if (options.id) {

        var customers = new Customers();
        customers.fetch({
            success: function (customers) {
   /* #1 --> */ var musketeers = customers.where({musketeerId: options.id});
                console.log(musketeers.length) //doesn't work as options.id is failing on last line
                var template = _.template($('#customer-list-template').html(), {
                    customers: customers.models
                });
                that.$el.html(template);
                console.log(customers.models);
            }
        });

    } else {
        var template = _.template($('#customer-list-template').html(), {});
        that.$el.html(template);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Although it isn't explicitly documented, Collection#where uses strict equality (===) when searching. From the fine source code:

where: function(attrs, first) {
  if (_.isEmpty(attrs)) return first ? void 0 : [];
  return this[first ? 'find' : 'filter'](function(model) {
    for (var key in attrs) {
      if (attrs[key] !== model.get(key)) return false;
    }
    return true;
  });
},

note the attrs[key] !== model.get(key) inside the callback function, that won't consider 10 (a probable id value) and '10' (a probable search value extracted from an <input>) to be a match. That means that:

customers.where({musketeerId: 10});

might find something whereas:

customers.where({musketeerId: '10'});

won't.

You can get around this sort of thing with parseInt:

// Way off where you extract values from the `<input>`...
options.id = parseInt($input.val(), 10);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...