【问题标题】:Optimizing my KnockOutJS function - From Ugly Code to Clean, How?优化我的 KnockOutJS 函数 - 从丑陋的代码到干净,如何?
【发布时间】:2019-12-04 23:51:28
【问题描述】:

功能说明

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

我接受 3 个参数:

  1. findBy = 是否通过“id”或“name”属性定位源索引。
  2. cmpVal = 我们在数组中搜索的值
  3. objNewItem = 新项目。本例前 { id: "12" , name: "NewName" }

然后我从数组中删除该索引,最后将新对象推入数组中。

我没有使用 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。

谁能帮我清理一下?我很聪明,知道它效率不高,但我不知道如何优化它。

任何建议将不胜感激。谢谢!

约翰

【问题讨论】:

    标签: javascript arrays knockout.js


    【解决方案1】:

    好吧……

    首先我们将创建一个包含所有逻辑的函数,从这个例子开始,你可以用它做任何事情。最合适的方法是直接在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());
    

    【讨论】:

    • 哇,非常感谢@MKougiouris!我可以看到这确实使它变得更加通用。 A++ 答案。
    猜你喜欢
    • 1970-01-01
    • 2021-10-30
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多