2016-08-24 71 views
1

在我的HTML页面中有3个输入。使用用户输入,我希望使用KnockoutJS更新我的页面元素。这是我写的脚本:在KnockoutJS中将数据推送到数组的问题

$(document).ready(function(){ 

    function Task(data){ 
     this.goal=ko.observable(data.goal); 
     this.type=ko.observable(data.type); 
     this.date=ko.observable(data.date); 
     console.log("Data"+ " " + data.goal); 

    } 



    var myViewModel=function(tasks){ 
     var self=this; 
     self.tasks=ko.observableArray([{goal:"abc", type:"Intermediate", date:"12/13/1122"}]); 
     self.newGoalText=ko.observable(""); 
     self.newTypeText=ko.observable(""); 
     self.newDateText=ko.observable(""); 


     self.addTask=function(){ 
      self.tasks.push(new Task({goal:this.newGoalText(),type:this.newTypeText(), date:this.newDateText()})); 

      console.log(tasks); 

     self.newGoalText(""); 
     self.newTypeText(""); 
     self.newDateText(""); 


    }//addTask function 

    }//viewModel 


    ko.applyBindings(new myViewModel()) 

}); 

console.log告诉我,值是从用户获得的预期。但是,任务数组上的“推”方法似乎根本没有效果。请指导我。

+0

问题可能在于你的html,所以它会有帮助,如果你发布它。我测试了你的代码(没有改变任何东西),它和我提供的标记一起工作。见https://jsfiddle.net/ffojupuf/ – Adrian

+0

@Adrian,谢谢你的帮助。我的HTML代码和你的类似,我没有发现很多不同的wrt绑定。不知道出了什么问题,但!我使用“值”而不是“textInput”。这是唯一的区别。 –

回答

1

如果要传递到您的阵列任务,你必须做的,每次,所以,当你初始化,你必须使用[new Task({...}), new Task({...})]

console.log(tasks);是不正确的。这是显示你的任务变量,而不是你的self.tasks,我想知道你想要显示什么,所以要小心你的变量名和(无)varname vs this.varname vs self.varname,否则你会有这么多头痛...

终于here you are你的例子充分工作。

我希望这对你有所帮助。

问候。

+0

谢谢!这工作! –