簡體   English   中英

突破每個下划線

[英]breaking out of an underscore each

我試圖在集合中找到一個屬性等於html選擇選項值的模型。

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

每當更改醫院名稱時,觸發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

找到具有屬性的locationModel后,我無法退出循環。 有幫助嗎? 此刻我已經調查了這一點但沒有成功。

如果您正在搜索第一場比賽,那么您使用了錯誤的方法。 收藏有大量的混合下划線方法 ,尤其是他們已經find在混合:

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

查看列表中的每個值,返回通過真值測試( 迭代器 )的第一個值,如果沒有值通過測試,則返回undefined

像這樣的東西:

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

如果您的模型中的name s已預先修剪並且干凈整潔,那么您可以使用findWhere

findWhere collection.findWhere(attributes)

就像在哪里一樣,但只直接返回集合中與傳遞的屬性匹配的第一個模型。

像這樣:

var name = $.trim($(this).val());
that.locationModel = locationListCollection.findWhere({ name: name });

順便說一下,這個:

console.log(locationModel);

不會給你任何東西,因為locationModelthat.locationModel是不同的東西。

你可以隨時去上學。

$('select[name="hospitalnames"]').change(function() {
   var name =  $(this).val();
   for (var i = 0; i < locationListCollection.length; ++i) {
     var locationModel = locationListCollection.models[i];
     if ($.trim(locationModel.get('name')) == $.trim(name)) {
        that.locationModel = locationModel;
        break;
     }
   }
});

嘗試這個,

var name =  $(this).val();
var flag=true;
locationListCollection.each(function(locationModel) {
  if (flag && $.trim(locationModel.get('name')) == $.trim(name)) {
     that.locationModel = locationModel;
     flag=false;
      //return false;// to break the $.each loop
  }
});

簡短就是沒有。

如果你看一下下划線的來源,你會看到他們使用一個破壞對象來快速停止.each(),但這只能在內部使用。

我不建議這樣做,但您可以隨時修改源以公開此斷路器對象(請參閱帶注釋的源http://underscorejs.org/docs/underscore.html中的基線設置)。 然后你只需返回此對象而不是返回false。 但您可能需要刪除本機forEach調用以保持行為一致。 所以這不值得!

_.each(function(arr) {
    if(condition) {
       return _.breaker; // Assuming you changed the source.
    }
});

由於您要搜索單個項而不是.each()使用:

 var locationModel = _.find(arr, function(item) {
    return $.trim(locationModel.get('name')) == $.trim(name);
 ));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM