【问题标题】:Updation of object inside observable array is done but changes are not coming on browser可观察数组内的对象更新已完成,但浏览器未发生更改
【发布时间】:2012-05-31 22:00:05
【问题描述】:

我现在面临一个问题。我有一个包含对象列表的可观察数组。每当我更新数组的任何对象的属性时。它不会反映在浏览器上。我已经使用了所有的淘汰功能,如替换、删除.但是更新来自可观察数组而不是浏览器。

这是我的问题的一个示例:

 var ViewModel=new {
     self=this;
     self.List=ko.observableArray([]); 
              }
     $(function(){
       ko.applyBinding(ViewModel); 
    }) 
    $.post('/url',{},function(data){
        ViewModel.List(data); //data is list having 4 property having CommentList as again object-->id,title,description,CommentList--->commenttitle,commentdescription
      })  
    //During change of property of commentList
    $.post('/updateComment',{},function(obj){//Here obj-->obj.Commenttitle="some title",obj.commentdescription='some description'
       //Let say there require update 4th object of List and  2nd property of CommentList
         ViewModel.AnswerList()[4].CommentList.splice(2,1,obj);

     })
    //But nothing updation on browser

【问题讨论】:

  • 请考虑将您的帖子编辑为精确的语言,并使用一些最少的代码来解决您的问题

标签: knockout.js


【解决方案1】:

你说:

每当我更新数组的任何对象的属性时,它都不是 反映在浏览器上。

observable 数组中对象的属性也需要设置为ko.observable,以便您的 UI 自动更新。

例如:

var anObservableArray = ko.observableArray([    
  { name: "A", type: "Type A" }    
]);

// some later point
anObservableArray()[0].name = "B";

不会更新您的 UI,因为 name 不是可观察的。

然而,

var anObservableArray = ko.observableArray([    
  { name: ko.observable("A"), type: ko.observable("Type A") }    
]);

// some later point
anObservableArray()[0].name("B");

..将更新您的 UI 以显示名称 B,因为 name 是可观察的。

编辑:(将代码添加到问题后)

所以从你的代码中你有:

 answer=GetAnswerFromViewModel(parentcourseItemID); 
 answer.CommentCount--;                     
 answer.CommentList.splice(CommentIndex,1); 
 answer.CommentText=''; 

假设 GetAnswerFromViewModel 返回具有可观察属性的答案,您应该这样写:

 answer=GetAnswerFromViewModel(parentcourseItemID); 
 answer.CommentCount(answer.CommentCount()--);                     
 answer.CommentList.splice(CommentIndex,1); 
 answer.CommentText(''); 

如果您的答案中的属性不是可观察的,那么您的 UI 将不会更新。

【讨论】:

  • 但问题是该阵列即将用于服务器端。
  • 目前还不清楚确切的问题是什么。如果您有来自服务器的数据,那么我建议您查看映射插件,它将 JSON 数据(例如您的数组)转换为可观察的属性。见knockoutjs.com/documentation/plugins-mapping.html
  • 实际上在映射中它是直接将数据传递给 observableArray。但在我的情况下,我从服务器端获取需要更新数组的对象,它也需要更新 UI
  • 如果我们将代码编写为 var listObj=ViewModel.AnswerList(); 更新 observableArray 中的对象后的另一件事ViewModel.Answer([]); ViewModel.Answer(listobj);然后它会更新 UI,否则不会。但这是不可取的。
猜你喜欢
  • 2020-12-12
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多