在集合中引用变量时出现问题.方法在渲染函数中

Trouble referencing variable in Collections.where method within render function

本文关键字:方法 函数 问题 集合 引用 变量      更新时间:2023-09-26

我在主干代码中遇到了一些麻烦。下面的代码涉及到一个呈现函数。我可以找回所有的模型。当我尝试使用"集合"时,问题就出现了。方法位于编号为#1的行。正如您所看到的,我已经将一个对象文字传递给了渲染函数,但是由于某种原因,我无法在客户中引用它。方法在第1行。当我给这个方法一个字面数字,比如45,它能工作。有没有什么方法可以让我把变量引用传递进去?

谢谢

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

虽然没有明确记录,但Collection#where在搜索时使用严格相等(===)。来自精美的源代码:

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

注意回调函数中的attrs[key] !== model.get(key),它不会考虑10(可能的id值)和'10'(从<input>中提取的可能的搜索值)是匹配的。这意味着:

customers.where({musketeerId: 10});

可能会找到一些东西,而

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

不会。

你可以用parseInt:

来解决这个问题
// Way off where you extract values from the `<input>`...
options.id = parseInt($input.val(), 10);