突破每个下划线

gee*_*ugi 2 javascript jquery backbone.js underscore.js

我试图在集合中找到一个属性等于html选择选项值的模型.

<div id="hospital-details">
    <select name="hospitalnames">
       <option><%- model.get('name') %></option>
    </select>
</div>
Run Code Online (Sandbox Code Playgroud)

每当更改医院名称时,触发jquery更改回调以查找具有所选选项值作为属性值的locationModel,如下所示,

$('select[name="hospitalnames"]').change(function() {
   var name =  $(this).val();
   locationListCollection.each(function(locationModel) {
     if ($.trim(locationModel.get('name')) == $.trim(name)) {
        that.locationModel = locationModel;
        return false; // control is returned to underscore.min.js
     }
   });
});
console.log(that.locationModel); // this is not being displayed at all
Run Code Online (Sandbox Code Playgroud)

找到具有属性的locationModel后,我无法退出循环.有帮助吗?此刻我已经调查了 这一点但没有成功.

mu *_*ort 9

如果您正在搜索第一场比赛,那么您使用了错误的方法.集合中混合了大量的Underscore方法,特别是它们find混合在:

_.find(list, iterator, [context])

查看列表中的每个值,返回通过真值测试(迭代器)的第一个undefined值,或者没有值通过测试.

像这样的东西:

var name = $.trim($(this).val());
that.locationModel = locationListCollection.find(function(locationModel) {
  return $.trim(locationModel.get('name')) == name;
});
Run Code Online (Sandbox Code Playgroud)

如果name模型中的s经过预先修整并且干净整洁,那么您可以使用findWhere:

findWhere collection.findWhere(attributes)

就像在哪里一样,但只直接返回集合中与传递的属性匹配的第一个模型.

像这样:

var name = $.trim($(this).val());
that.locationModel = locationListCollection.findWhere({ name: name });
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这个:

console.log(locationModel);
Run Code Online (Sandbox Code Playgroud)

不会给你任何东西因为locationModel而且that.locationModel是不同的东西.