Subscribe to observable array for new or removed entry only

前端 未结 6 1051
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 12:39

So yes I can subscribe to an observable array:

vm.myArray = ko.observableArray();
vm.myArray.subscribe(function(newVal){...});

The problem

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 13:11

    I am using a similar but different approach, keep track whether an element has been instrumented in the element itself:

    myArray.subscribe(function(array){
      $.each(array, function(id, el) {
        if (!el.instrumented) {
          el.instrumented = true;
          el.displayName = ko.computed(function(){
            var fn = $.trim(el.firstName()), ln = $.trim(el.lastName());
            if (fn || ln) {
              return fn ? (fn + (ln ? " " + ln : "")) : ln;
            } else {
              return el.email();
            }
          })
        }
      });
    })
    

    But it is really tedious and the pattern repeated across my code

提交回复
热议问题