knockout.js 优化我的KnockOutJS函数-从丑陋的代码到干净,如何?

wecizke3  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(144)

功能说明

这个函数应该只是替换我的可观察数组中的一个项。

我接受3个参数:

  1. findBy =是否按“id”或“name”属性查找源索引。
  2. cmpVal =要在数组中搜索的值
  3. objNewItem =新项目。本例示例为{ id:“12”,姓名:“新名称”}
    然后我从数组中删除该索引,最后将新对象推入数组。
    我没有运气使用Knockout中的替换函数,所以我不得不自己写。
    我知道这可能是互联网上最丑陋的代码。这就是为什么我在这里听从你们专业人士。:)
/* Update A Station 
  *
  *  @param   findBy      string    Property to find ( "id" or "name")
  *  @param   cmpVal      string    Value to compare against
  *  @param   objNewItem  object    The new object replacing old
  * */
  self.modifyStation = function(findBy, cmpVal, objNewItem){

    var sourceIndex;
    var oldId;

    /* Find Index Of Old Station */
    var c = -1;
    ko.utils.arrayForEach(this.station(), function(item) {
      c++;
      switch (findBy) {

        case "id":
          var value = item.id();
          if(value == cmpVal){
            sourceIndex = c;
            oldId = item.id();
          }
          break;

        case "name":
          var value = item.name();
          if(value == cmpVal){
            sourceIndex = c;
            oldId = item.id();
          }
          break;
      }

    });

    /* Remove Old */
    self.station().splice(sourceIndex,1);

    /* Insert New Station 
    *  [For Now] not allowing updating of ID. Only
    *  can update the other properties (yes, I realize that
    *  only leaves "name", but more will be added )
    */
    objNewItem.id = oldId;  // Put old ID back in
    self.station.push(objNewItem);

  }

**注意:**我暂时不允许他们编辑ID.

有人能帮我清理一下吗?我很聪明,知道它效率不高,但我不知道如何优化它。
任何建议都将不胜感激。谢谢!
若翰

enyaitl3

enyaitl31#

好吧那么...
首先我们将创建一个包含所有逻辑的函数,从这个例子开始,你可以用它做任何事情。最正确的方法是直接在knockout上扩展你的'observableArray',但是我现在不打算做这么多:P

function ReplaceInObservableArray(obsArray, prop, cmpVal, newItem){
    // use the fact that you can get the value of the property by treating the object as the dictionary that it is
  // so you do not need to program for specific properties for different array model types
    var foundItems = obsArray().filter(function(i){ 

        return ko.utils.unwrapObservable(i[prop]) == cmpVal;
    });

    if(foundItems.length > 1) 
    {
      // handle what happens when the property you are comparing is not unique on your list. More than one items exists with this comparison run
      // you should throw or improve this sample further with this case implementation.
    } else if(foundItems.length == 0) 
    {
        // handle what happens when there is nothing found with what you are searching with.
    } else {
        // replace at the same index rather than pushing, so you dont move any other items on the array
        // use the frameworks built in method to make the replacement
        obsArray.replace(foundItems[0], newItem);
    }
}

var demoArray = ko.observableArray([{ id : 1, name : 'test1' },{id : 2, name : 'test2' },{ id : 3, name : 'test3'},{id : 4, name : 'test4'}]);
ReplaceInObservableArray(demoArray,'id', 1, {id : 1, name : 'test111'});
ReplaceInObservableArray(demoArray,'name', 'test3', {id : 3, name : 'test3333'});
console.log(demoArray());

相关问题