Knockoutjs how to dynamically load external file as a template data source in component

Source: Internet
Author: User

Played Knockoutjs know, there is a powerful function called component, and this component has a good place is to have their own viewmodel and template,

such as the following:

Ko.components.register (' Message-editor ', {            function() {},            Template: ' "        });   

Obviously, ViewModel is the function area, and the template is the stencil area, and then registers the component with the knockout through the Register function, below we demonstrate a simple

is the ability to dynamically display the length of the current "input" content.

<!DOCTYPE html><Html><Head><MetaHttp-equiv= "Content-type"Content= "text/html; Charset=utf-8 "/><Title></Title><MetaCharSet= "Utf-8"/><ScriptSrc= "Jquery-1.8.2.js"></Script><ScriptSrc= "Knockoutjs.js"></Script></Head><Body><DivData-bind= ' Component:"Message-editor" '></Div><ScriptType= "Text/javascript">Ko.components.register (‘Message-editor‘, {viewModel:function(params) {This. text=Ko.observable (params&&Params.initialtext| |  "message: <input data-bind= "Value:text"/>  "+ Span style= "color: #000000;" > ' 

Take a closer look at the code, and the current component will inject the template to the HTML div tag, and the template tag has a binding to the text element.

The data source for this (text (). length) is exactly the This.text in ViewModel. Right... With these two in one, our final HTML display is as follows:

Then we randomly enter some numbers, move the mouse, this time will trigger the input change event, such as the following.

Isn't it good to hang??? Of course, some people may ask, if the input is given a little default value??? Can you do that? Of course, this time we can

Data-bind The default value is OK ... such as the following:

1<Body>2<H4>second instance, passing parameters</H4>3<DivData-bind= ' Component:{Name: "Message-editor", params: {initialtext: "Hello, world!"}} '></Div>45<ScriptType= "Text/javascript">67Ko.components.register (‘Message-editor‘, {8ViewModel:function(params) {9This. text=Ko.observable (params&&Params.initialtext||‘‘);10},11Template ' message: <input data-bind= "Value:text"/>  ' 

As you can see, in the code above I add a initialtext attribute to the params object in component, and this time it is possible to inject this initialtext dynamically into

In our ViewModel, and then our input and span elements subscribe to the This.text monitoring attribute in this viewmodel via Data-bind, and this time the real-time update exercise

Have done, can't wait to look at it ~

One: Problem analysis

Well, through the above demonstration, you may find the following two questions, the first problem is good strong, as long as you register on it, there is no need to go through the applybindings

Apply a viewmodel, so that the page is modular, really good convenient ~ so this question is a good thing, the second problem is that the content of our template templates is

In the form of "hard coding", that is, if this content has many, such as 100 lines, 200 lines, then we are not crazy??? Is that you can no longer be able to one by one splicing up, even if

Together, maintenance costs are too big, so the question comes, how to dynamic template content??? For example, the reality of the Baidu Library we see the page ... Such as:

This page, there are a lot of modules, such as I circled out of the top 3, the three modules of the HTML must be a lot of it ~ ~ ~

Two: Template dynamic acquisition

HTML content dynamic acquisition, usually there are two ways, the first is Requirejs, of course, you need to reference such a JS, the second is that we rewrite their template, of course, this article I

We explain the latter way, we have to do is to rewrite the component in the LoadTemplate function, and then replace the default Defaultloader loader, is not very simple???

1. Overriding the LoadTemplate method

//First step: Overriding the LoadTemplate methodvar Templatefromurlloader ={loadtemplate:function (name, Templateconfig, callback) {if (Templateconfig.fromurl) {var fullurl = '/' + Templateconfig.fromurl //ajax dynamically gets the external file content $.get ( FullUrl, function (markupstring) { Ko.components.defaultLoader.loadTemplate (name, markupstring, callback); }); } else {callback (null< Span style= "color: #000000;" >); } }}; // Replace the original Defaultloader, Implement the new TemplateFromUrlLoaderko.components.loaders.unshift (Templatefromurlloader);       

2. Put the hard codeing into the external file, such as I created a new file.html.

3. Register the component, then refer to the outer file path on the template tag, such as the following {fromurl: ' file.html '}

        Ko.components.register (' Message-editor ', {            function (params) {                this.text = ko.observable ( Params && Params.initialtext | | ');            },            ' file.html ' },});      

OK, all the features are ready, let's go through the page and see what it is like???

Finally the merit has become, is not to sprinkle ~ ~ ~ then can be extended to the above introduction of the "Baidu Library" example, we can put the HTML of each module into a separate file,

Yes, well, this article is here, I hope to help you ~ ~ ~

View Code

Knockoutjs how to dynamically load external file as a template data source in component

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.