A summary of MVC MVVM Knockout frequently encountered problems

Source: Internet
Author: User
Tags convert json to string javascript array ruby on rails

1. Template binding (using plugin Jquery.tmpl)

var viewmodel={product:ko.observable ()}

    <div data-bind= "template:{name: ' Templatepropertys '}" ><div>    <script type= "text/html" id= " Templatepropertys ">        {each (I,item) Product (). custom Property Set}}        <div class=" Form-group "> <label for            = "InputEmail3" class= "col-lg-2 Control-label" data-bind= "Text:item". Key "></label>            <div class=" col-sm-10 ">                <input type=" email "class=" Form-control "id=" InputEmail3 "placeholder=" Email "data-bind=" Value:item. Value >            </div>        </div>        {{/each}}    </script>

When writing the set of each object, please note that the properties of the ViewModel must be ' () ', the object within the Property object does not need to add ' () '

2, about the double binding of KO

Ko.cleannode (document.getElementById ("Divcatalog"));//Clear bindings
Ko.applybindings (CATALOGVM, document.getElementById ("Divcatalog"));//rebind again

3. Convert view model data to JSON format

Ko.tojs-clones your view model object and replaces all of the observable objects with the current values, so you can get a clean and knockout-independent copy of the data.

 ko.tojson-convert the View model object to a JSON string. The principle is: first tune the KO.TOJS on the view model and then invoke the native JSON serializer of the browser to get the results. Note: Some old browser versions do not support native JSON serializers (for example: IE7 and previous versions), you need to refer to Json2.js class library.

4. Update view model data with JSON

If you get the data from the server side and update to the view model, the simplest way is to implement it yourself. For example

Load and parse the Jsonvar Somejson =/* Omitted:fetch it from the server however you want */;var parsed = Json.parse ( Somejson);//Update View model Propertiesviewmodel.firstname (parsed.firstname); Viewmodel.pets (parsed.pets);

5.. NET C # Asynchronously submits the JSON model to the background

var d = Ko.tojs (Baseinfo);
var c = json.stringify (d);//convert JSON to String

6. Operation Observablearray

IndexOf

The IndexOf method returns the first index in the array that equals your incoming parameter entry, such as Myobservablearray.indexof (' blah '), which returns the array index of the first array item equal to blah from 0, or 1 if no matching record is found.

Slice

The slice function is a slice method that observablearray equivalent to native JavaScript, which returns a collection of all objects from the start index to the end index. Call Myobservablearray.slice (...) Equivalent to calling Myobservablearray.slice (...) Method.

Operation Observablearray

Observablearray provides a simple set of methods to manipulate the contents of an array and inform subscribers.

Pop, push, shift, unshift, reverse, sort, splice

These methods are equivalent to using native JavaScript methods to manipulate arrays, the biggest difference being that they inform the subscriber array of changes.

Myobservablearray.push (' Some new value ') adds a new item at the end of the array

Myobservablearray.pop () Moves the last item of the array and returns it

Myobservablearray.unshift (' Some new value ') Inserts a new item in the array header

Myobservablearray.shift () Moves the first item in the divisor group and returns it

Myobservablearray.reverse () Flips the order of the entire array

Myobservablearray.sort () Sorting the contents of an array

By default, the order is sorted by character (if it's a string) or by number (in the case of a number)

Alternatively, you can sort the array by passing in a sort function. This sort function takes two parameters (representing the two items to compare) and returns-1 if the first item is less than the second item, or greater than 1; Returns 0.

For example: Using LastName to sort person objects, you can write:

    1. Myobservablearray.sort (function (left, right) {
    2. return left.lastname = = Right.lastname? 0: (Left.lastname < right.lastname? -1:1)
    3. });

Myobservablearray.splice () deletes the specified index and the specified number of array element objects. For example: Myobservablearray.splice (1, 3) deletes 3 elements starting from 1 and returns the 3 elements as an array of elements. For more information about Observablearray functions, refer to the documentation for standard JavaScript array functions.

Remove and RemoveAll

Observablearray adds a number of function methods that are useful but do not have a default JavaScript array.

Myobservablearray.remove (Someitem) removes all array items whose values are equal to Someitem and returns the deleted elements as an array

Myobservablearray.remove (function (item) {return Item.age < 18}) removes all elements of the Age property less than 18 of the array item and returns the deleted element as an array

Myobservablearray.removeall ([' Chad ', undefined]) removes all array items whose values are equal to ' Chad ', 132, undefined, and returns the deleted element as an array

Myobservablearray.removeall () deletes all array items and returns the deleted elements as an array

Destroy and Destroyall

(note: Usually only with Ruby on Rails developers)

The Destroy and Destroyall functions are developed for use by Ruby on Rails developers:

Myobservablearray.destroy (Someitem) finds all array element objects with values equal to Someitem and adds _destroy properties to them, assigning true

Myobservablearray.destroy (function (someitem) {return Someitem.age < 18}) finds all elements of an array element whose age property is less than 18 and adds _destroy The property of the value, assigned to True

Myobservablearray.destroyall ([' Chad ', undefined]) finds all array element objects whose values are equal to ' Chad ', 132, undefined, and adds _destroy properties to them, Assignment is True

Myobservablearray.destroyall () adds a _destroy property to all element objects, assigning true

So, what is _destroy for? As I mentioned, it's just for rails developers. In the rails development process, if you pass in a JSON object, the Rails framework is automatically converted to a ActiveRecord object and saved to the database. The Rails framework knows which objects are present in the database and what needs to be added or updated, and the tag _destroy is true to tell the framework to delete the record.

Note: When Ko render a foreach template, an element with the _destroy attribute and a value of true are automatically hidden. So if your "delete" button calls the Destroy (Someitem) method, the corresponding elements on the UI interface will be automatically hidden, and then when you commit the JSON object to rails, This element item will be deleted from the database (while other element items will be inserted or updated normally).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.