3.knockout.js website Learning (visible binding)

Source: Internet
Author: User

Objective

Lets the visible bind to a DOM element so that the hidden or visible of the element depends on the value of the binding.

A simple binding

First of all, we should define a ViewModel

    var Appviewmodel = {        shouldShowMessage:ko.observable (True)///   initialization div is visible      }; Appviewmodel.shouldshowmessage = ko.observable (// now hidden le ko.applybindings (appviewmodel);   

And activate the knockout via Ko.applybindins.

Then define a UI interface element

<div data-bind="visible:shouldshowmessage" >    "shouldshowmessageTrue  value.</div>       

After the run, this div is still displayed at initialization time, and is then re-assigned to false, causing the div to be hidden.

Parameters:

When the parameter is set to a false value (for example: A Boolean value of false, a numeric value of 0, or null, or undefined), the binding sets the element's Style.display value to none, allowing the element to be hidden. It has a higher priority than any display style you define in CSS.

When the parameter is set to a true value (for example, Boolean, or a non-empty Non-null object or array), the binding removes the Style.display value of the element and makes the element visible. Then your custom display style in CSS will automatically take effect.

If the parameter is a monitoring attribute observable, the visible state of the element will change depending on the value of the parameter, and if not, the visible state of the element will be set only once and not later.

Use a function or expression to control the visibility of an element

You can also use a JavaScript function or an expression as an argument. In this case, the result of the function or expression will determine whether to show/hide the element. For example:

<script type= "text/javascript" > var appviewmodel = {ShouldShowMessage:ko.obse Rvable (true), /// MyValues:ko.observableArray ([])}; Appviewmodel.shouldshowmessage = ko.observable (false); /// now hidden le AppViewModel.myValues.push ( "some value"); /// add an item to the myvalues array          

Added a Myvalues property value in ViewModel

Adds an item to the Myvalues array at the same time

and binds an element in the page UI

<div data-bind="visible:myvalues (). length > 0" >    
'myvalues' has at least one member.
</div>

That's it. When you have finished adding the "some value" element, Myvalues (). Length>0 The result is true

Then this div will show up.

Objective

Text is bound to a DOM element so that the element displays a literal value for the parameter you are binding. This binding is useful on display <span> or <em>, but you can use it on any element.

Simple binding

 today ' s message is: <span data-bind= "text: Mymessage "></span> <script type=" text/ Javascript "Src=" ~/ Scripts/knockout-2.3.0.debug.js" ></script> <script type= "text/javascript" > var viewModel = {myMessage:ko.observable ()}; Viewmodel.mymessage ( " "); Ko.applybindings (ViewModel); </script>          

Ko sets the parameter value to the element's innertext (IE) or Textcontent (Firefox and other similar browser) properties. The original text will be overwritten.

If the parameter is a observable of the monitoring property, the text of the element will be updated according to the value of the parameter, and if not, the text of the element will be set only once and not later.

If you pass a number or string (such as an object or an array), the text displayed will be the equivalent of yourparameter.tostring ().

Use a function or an expression to determine the text value

Continue to add a property in the ViewModel above and add a dependency monitoring property

Price:ko.observable (24.95)    viewmodel.pricerating = ko.dependentobservable (        function () {         " Expensive" affordable ";}, ViewModel);        

Add a UI page element to bind

is <span data-bind="text:pricerating" ></span> today.  

Text text will now be replaced between "expensive" and "affordable", depending on how the price changes.

About HTML Encoding

Because the binding is the innertext or textcontent of the set element (not the innerHTML), it is safe, without the risk of HTML or script injection. For example: If you write the following code:

Viewmodel.mymessage ("<i>hello, world!</i>");  

It does not display italic characters, but instead prints the labels as-is. If you need to display HTML content, please refer to HTML bindings.

About the white space of IE 6 whitespace

IE6 has a strange problem, if there is a space in span, it will automatically become an empty span. If you want to write the following code, that knockout will have no effect:

HTML binding

HTML is bound to a DOM element so that the HTML value displayed by the element is a parameter that you bind. This is useful if you declare the HTML tag and render it in your view model.

Simple example

<div data-bind="html:details" ></div> <script type="Text/javascriptvar ViewModel = {details:ko.observable ()}; ko.applybindings (ViewModel); Viewmodel.details ("<em>for Further details, view the report <a href= ' report.html ' >here</a>.</em>');</script> 

So the EM tag of the HTML will be displayed in this

Ko sets the parameter value to the element's innerHTML property, and the content before the element is overwritten.

If the parameter is a observable of the monitoring property, the element's contents will be updated according to the value of the parameter, and if not, the element's contents will be set only once and not later.

If you pass a number or string (such as an object or an array), the text displayed will be the equivalent of yourparameter.tostring ().

About HTML Encoding

Because the binding sets the innerHTML of the element, you should be careful not to use unsafe HTML code, as it is possible to cause a script injection attack. If you're not sure if it's safe (such as displaying user input), then you should use the text binding, because this binding simply sets the text value of the element innertext and textcontent.

CSS Bindings

The CSS binding is to add or remove one or more CSS classes onto the DOM element. Useful, such as highlighting when a number becomes negative. (Note: If you do not want to apply CSS class but want to refer to the Style property, refer to the style binding.) )

Simple example

<p style="Background:gray; Color: #ffffff; font-size:18pt; ">html bindings </p>  
<script type="text/javascript" >       var viewModel = {                details:ko.observable (),        CurrentProfit:ko.observable (150000)}; ko.applybindings (ViewModel); Viewmodel.currentprofit (-  ); Viewmodel.details ("<em>for further details, view the report <a href= ' report.html ' >here</a >.</em>"             

The effect after operation is

I remember writing a CSS style.

. profitwarning {    color:red;}

This parameter is a JavaScript object, the property is your CSS class name, the value is a comparison of true or false, to determine whether this CSS class should be used.

You can set more than one CSS class at a time. For example, if your view model has a property called Isservre,

<div data-bind="css: {profitwarning:currentprofit () < 0, majorhighlight:issevere}" > /c2>

If the parameter is a observable of the monitoring property, the CSS class on that element will be automatically added or deleted as the value changes. If not, the CSS class will only be added or deleted once and not updated at a later time.

You can use any JavaScript expression or function as a parameter. Ko will use its execution results to decide whether to apply or delete the CSS class.

The name of the applied CSS class is not a valid JavaScript variable named

If you want to use My-class class, you can't write this:

<div data-bind="css: {my-class:somevalue}" >...</div>  

Because My-class is not a valid name. The solution is to use quotation marks on both sides of the my-class as a string. This is a legitimate JavaScript object literal (from the JSON specification, you should use it at any time, although not required). For example

<div data-bind="css: {' My-class ': somevalue}" >...</div>  

Style bindings

The style binding is to add or remove a style value on one or more DOM elements. For example, when a number becomes negative, it is highlighted, or the corresponding width bar is displayed according to the number. (Note: If you are applying a CSS class instead of applying a style value, refer to CSS bindings.) )

Style Simple Example

<div data-bind="Style: {color:currentprofit () < 0? ' Red ': ' Black '}"> Profit information</div><script type="text/javascript"src="~/scripts/ Knockout-2.3.0.debug.js"></script> <script type="text/javascript"> var ViewModel = {currentProfit:ko.observable (15000)}; Viewmodel.currentprofit (-); Ko.applybindings (ViewModel);</script>            

Simple sample code, which was found to be red after running the font

When Currentprofit is less than 0, the DIV's style.color is red, which is greater than black.

The parameter is a JavaScript object, the property is the name of your style, and the value is the value that the style needs to apply.

You can set multiple style values at once. For example, if your view model has a property called Isservre,

<div data-bind="style: {color:currentprofit () < 0? ' Red ': ' Black ', fontweight:issevere ()? ' Bold ': '} '>...</div>  

If the parameter is a observable of the monitoring property, the style value on the element is automatically added or deleted as the value changes. If not, the style value is applied only once and is not updated at a later time.

You can use any JavaScript expression or function as a parameter. Ko will use its execution results to decide whether to apply or remove the style value.

The name of the applied style is not a valid JavaScript variable named

If you need to apply Font-weight or text-decoration, you cannot use it directly, but instead use the JavaScript name of the style.

Error: {font-weight:somevalue}; Correct: {Fontweight:somevalue}

Error: {text-decoration:somevalue}; Correct: {Textdecoration:somevalue}

Reference: A style name and a list of corresponding JavaScript names

attr binding

The attr binding provides a way to set any property value for a DOM element. You can set the SRC attribute of the IMG to connect the href attribute. With bindings, when the model property changes, it is automatically updated.

attr Binding Simple Example

<a data-bind="attr: {href:url, title:details}" >    report</a><script type="  Text/javascriptvar ViewModel = {url:ko.observable ("year-end.html"), details: Ko.observable ("reportincluding final year-end statistics")}; Ko.applybindings (ViewModel);</script>            

The post-run effect is

The render result is that the href attribute of the connection is set to Year-end.html, and the title property is set to report including final year-end statistics

The parameter is a JavaScript object, the property is your attribute name, and the value is the value that the attribute needs to apply.

If the parameter is a observable of the monitoring property, the attribute value on the element will be automatically added or deleted as the value changes. If not, the attribute value will be applied only once and not later in the update.

The attribute name applied is not a valid JavaScript variable named

If the property name you want to use is data-something, you can't write this:

<div data-bind="attr: {data-something:somevalue}" >...</div>  

Because data-something is not a valid name. The solution is to use quotation marks on both sides of the data-something as a string. This is a legitimate JavaScript object literal (from the JSON specification, you should use it at any time, although not required). For example

<div data-bind="attr: {' data-something ': somevalue}" >...</div>  

3.knockout.js website Learning (visible binding)

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.