Trouble referencing variable in Collections.where method within render function

后端 未结 1 576
忘了有多久
忘了有多久 2020-12-07 05:56

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 t

相关标签:
1条回答
  • 2020-12-07 06:33

    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);
    
    0 讨论(0)
提交回复
热议问题