Reputation: 55200
I am populating a complex view-model using MVC4. I am populating like this
var job = @Html.Raw(Json.Encode(Model.job));
var customer = @Html.Raw(Json.Encode(Model.customer));
var listTasks = @Html.Raw(Json.Encode(Model.Tasks));
var estimateMaterials = @Html.Raw(Json.Encode(Model.estimateMaterials));
var estimate = @Html.Raw(Json.Encode(Model.estimate));
var JobPost = {
customer: customer,
job: job,
listTasks: ko.observableArray(listTasks),
estimateMaterials: ko.observableArray(estimateMaterials),
estimate: ko.observable()
};
ko.applyBindings(JobPost, document.getElementById("update-job-form"));
Now, the object estimateMaterials
is being populated to a row. And to that row, I want to add Remove
to each row and Add button
at the bottom of the table like this
Then I saw, rniemeyer wonderful fiddle on adding / deleting row easily.
The forked fiddle is: http://jsfiddle.net/codovations/tDV9k/
In that there is a snippet like this
self.addLine = function() { self.lines.push(new CartLine()) };
self.removeLine = function(line) { self.lines.remove(line) };
I would like to implement something like that to my observable array
estimateMaterials: ko.observableArray(estimateMaterials)
Is this possible to add methods like this?
P.S: I am adding / deleting by cloning a row / removing closest tr respectively using jquery. I am seeking a cleaner way.
Update:
The main problem I am facing here is how to access the object in the observableArray
Upvotes: 0
Views: 398
Reputation: 10254
I might have understood your question incorrectly, have a look at the below and let me know if you have any questions
function EstimateMaterialLine() {
var self = this;
self.EstMatlID = ko.observable();
//other observables to follow
}
var job = @Html.Raw(Json.Encode(Model.job));
var customer = @Html.Raw(Json.Encode(Model.customer));
var listTasks = @Html.Raw(Json.Encode(Model.Tasks));
var estimateMaterials = @Html.Raw(Json.Encode(Model.estimateMaterials));
var estimate = @Html.Raw(Json.Encode(Model.estimate));
var JobPostViewModel = function(){
var self = this;
self.customer = ko.observable(customer);
self.job = ko.observable(job);
self.listTasks = ko.observableArray(listTasks);
self.estimateMaterials = ko.observableArray(estimateMaterials);
self.estimate = ko.observable(estimate);
self.removeEstimateMaterial = function(line) {
self.estimateMaterials.remove(line)
};
self.addEstimateMaterial = function() {
self.estimateMaterials.push(new EstimateMaterialLine())
};
};
var model = new JobPostViewModel();
ko.applyBindings(model, document.getElementById("update-job-form"));
So lets say you have a table, then you can use it like so:
<table data-bind="foreach: estimateMaterials">
<tr>
<td> <input type="button" value="delete" data-bind="click: $root.removeEstimateMaterials"/> </td>
<tr>
</table>
<input type="button" value="Add" data-bind="click: $root.addEstimateMaterials"/>
Upvotes: 1