Sakthivel
Sakthivel

Reputation: 666

Jquery html data-bind attribute use of its

I've come across this kind of codes on my HTML file, Here, i just to want to understand what is this data-bind attribute and its values(example: visible: tabs.active().value === 'sourceXml'). what it does here? Any one kindly explain.

<div style="border: solid #ddd; border-width: 0 1px 1px 1px; padding: 16px 12px 8px 12px; margin-top: -20px">
    <div data-bind="visible: tabs.active().value === 'sourceXml'">
    <div data-bind="template: { name: 'sourceXml', data: sourceXml }"></div>
</div>

<div data-bind="visible: tabs.active().value === 'searchTerms'">
    <div data-bind="template: { name: 'searchTerms', data: searchTerms }"></div>
</div>

<div data-bind="visible: tabs.active().value === 'outputFormat'">
    <div data-bind="template: { name: 'outputFormat', data: outputFormat }"></div>
</div>

<div data-bind="visible: tabs.active().value === 'savedQueries'">
    <div data-bind="template: { name: 'savedQueries', data: savedQueries }"></div>
</div>
</div>

Upvotes: 10

Views: 18227

Answers (1)

Casey Falk
Casey Falk

Reputation: 2667

Clarifying

1.) The data-bind attribute isn't jQuery -- it is an HTML5 attribute nearly exclusive to knockout.js (source). Data-bindings allow knockout.js to easily associate variable with DOM elements, apply templating schemes, or even apply conditional styling.

jQuery has a similarly-named .data() method that lets you access data attributes of elements, but that is not the same thing as data-bind.

The jQuery Docs detail more about the .data() method, but note that "as of jQuery 1.4.3 HTML5 data- attributes will be automatically pulled in to jQuery's data object" (emphasis mine). This is not specific to data-binding. Using data-binding in jQuery has no special effects.


What's The Point?

2.) The "visible" and "template" bits are just explaining what knockout.js should do with the bound data. There are lots of options, for example one easy-to-understand one is text (source):

<div>My favorite string is: <span data-bind="text: myString"></span></div>

Basically we are just preparing to apply a variable myString to the page once knockout.js loads the template.

Regarding visible the docs say, "The visible binding causes the associated DOM element to become hidden or visible according to the value you pass to the binding" (source).

Similarly, template "populates the associated DOM element with the results of rendering a template" (source)

So your example is checking which template is being used, constructs it in the div, and then makes it visible (while hiding the other "unused" templates).

Upvotes: 12

Related Questions