Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...