React-knockout seamless adhesion, the JavaScript project in the MVVM framework for the control of

Source: Internet
Author: User



This is about the use of react and knockout examples, two frameworks have their strengths, there are different features and characteristics, this time to combine them, it seems a little daring, but sometimes it is easy to encounter some strange needs. Make us have to go out some odd strokes. But is it really strange? In fact, this is not the way to create a control using react, and then use knockout to build the MVVM framework, the development process can become a non-flocculation, easy to expand maintenance, while enabling code reuse, reduce the workload of development.



1. To build the React-knockout MVVM framework we first need to download the JS library for react and Knockout



react:http://facebook.github.io/react/



knockout:http://knockoutjs.com/



2. After the download is complete, the react and knockout library files are imported into the project, and I have built the framework folder to place these frame files in the project volume.






3. In order for react and knockout to be fused, a special process needs to be done to create a new Knockoutreact.js file in the Framework folder and add the following code to it.


var KnockoutMixin = {

    updateKnockout: function () {
        this .__ koTrigger (! this .__ koTrigger ());
    },

    componentDidMount: function () {
        this .__ koTrigger = ko.observable (true);
        this .__ koModel = ko.computed (function () {
            this .__ koTrigger (); // subscribe to changes of this ...

            return {
                props: this.props,
                state: this.state
            };
        }, this);

        ko.applyBindings (this .__ koModel, this.getDOMNode ());
    },

    componentWillUnmount: function () {
        ko.cleanNode (this.getDOMNode ());
    },

    componentDidUpdate: function () {
        this.updateKnockout ();
    }
};

var reactHandler = ko.bindingHandlers.react = {
    render: function (el, Component, props) {
        React.render (
            React.createElement (Component, props),
            el
        );
    },

    init: function (el, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var options = valueAccessor ();
        var Component = ko.unwrap (options.component || options. $);
        var props = ko.toJS (options.props || viewModel);

        reactHandler.render (el, Component, props);

        return {controlsDescendantBindings: true};
    },

    update: function (el, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var options = valueAccessor ();
        var Component = ko.unwrap (options.component || options. $);
        var props = ko.toJS (options.props || viewModel);

        reactHandler.render (el, Component, props);

        return {controlsDescendantBindings: true};
    }
};


The first paragraph in this piece of code is to add the knockout binding mechanism to the react file, and the second code is to implement a UI element that is directly bound to create a control, such as using <div data-bind= "react: {$: Customtextbox, props: $data}><div> can create a Customtextbox control directly in HTML.



4. Let's create a control login and place it in the folder controls, the file name is called LOGIN.JSX


/**
 * data bind datas
 *      1. username 用户名
 *      2. password 密码
 *      3. loginCommand 登录事件
 */

var UserLogin = React.createClass({
    mixins: [ KnockoutMixin ],

    getDefaultProps:function(){
        return {
            labelUsername:  "Username",
            labelPassword:  "Password",           
        };
    },

    render: function(){
        return <div style={{marginTop: 20, marginLeft: 20}}>
                    <div>
                        <label>{this.props.labelUsername}</label>
                        <input type="text" style={{marginLeft: 20}}
                               data-bind="value: props.username"/>
                    </div>
                    <div style={{marginTop: 10}}>
                        <label>{this.props.labelPassword}</label>
                        <input type="text" style={{marginLeft: 20}}
                               data-bind="value: props.password"/>
                    </div>
                    <div style={{marginTop: 20, marginLeft: 150}}>  
                        <button data-bind="click: props.loginCommand"
                                style={{width:100}}>Login</button>  
                    </div>  
               </div>;
    },
});


Control in the user name username, password password, login operation Logincommand is to adapt to knockout data-bind binding, the control will be referenced in a view and then bound to ViewModel, After the ViewModel data has changed, the UI of the control will follow the changes and what it will look like, continue with the following steps.



5. Create a login interface login.html in the View folder. On this page, Data-bind react is used to create the login control for our previous step, and a new ViewModel is created in the following JS code and bound to the UI.

<! DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title id = "title"> Login </ title>

<script type = "text / javascript" src = "../ framework / react.js"> </ script>
<script type = "text / javascript" src = "../ framework / knockout-v3.3.0.js"> </ script>
<script type = "text / javascript" src = "../ framework / JSXTransformer.js"> </ script>
<script type = "text / javascript" src = "../ framework / knockoutReact.js"> </ script>

<script type = "text / jsx" src = "../ controls / login.jsx"> </ script>

<script type = "text / javascript" src = "../ viewmodel / loginViewModel.js"> </ script>
</ head>
<body style = "background: lightblue">
<div style = "margin-left: 30px">
<button data-bind = "click: viewModel.fillInfo"> Fill username and password </ button>
<button data-bind = "click: viewModel.clear"> Clear </ button>
</ div>

<div data-bind = "react: {$: UserLogin,
props: {
username: username,
password: password,
loginCommand: viewModel.startLogin.bind ($ data)
}
} ">
<div>
</ body>

<script type = "text / jsx">
var viewModel = new loginViewModel ();

    ko.applyBindings (loginViewModel);
</ script>

</ html>

The bound elements are

               username: username, the username of the control is bound to the username of the View Model
               password: password, the password of the control is bound to the password of the View Model
               loginCommand: viewModel.startLogin.bind ($ data) The loginCommand of the control is bound to the startLogin method of View Model

6. Create a new viewmodel folder and add loginViewModel.js to it. This is the viewmodel file for the login view and handles the logic needed in the login view.

var loginViewModel = (function () {
    function loginViewModel () {
        this.username = ko.observable ();
        this.password = ko.observable ();
    }

    / **
     * Login operation
     * /
    loginViewModel.prototype.startLogin = function () {
    var name = this.username ();
    var secure = this.password ();

        alert ("Username:" + name + "\ nPassword:" + secure);
    }

    / **
     * Fill in username and password
     * /
    loginViewModel.prototype.fillInfo = function () {
        this.username ("YLD");
        this.password ("123");
    }

    / **
     * Clear username and password
     * /
    loginViewModel.prototype.clear = function () {
        this.username ("");
        this.password ("");
    }

    return loginViewModel;
}) ();

7. The project is created and implemented. Now run it. I use google chrome browser here, and then for this project to work successfully in the browser, we must do a special treatment. Right-click the chrome browser shortcut and open the properties. Add --disable-web-security after the target

The effect of project operation is as follows

Source code: http://download.csdn.net/detail/leyyang/9022673
Copyright statement: This article is an original article of the blogger, and the detailed link of this article must be noted when reprinting, otherwise the author will retain its legal responsibility.

React-Knockout seamless glue, control of JavaScript project MVVM framework

Related Article

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.