1.Model学习(Backbone Tutorials)

本文介绍了Backbone.js的基本用法,包括模型创建、属性设置与获取、监听模型变化及与服务器交互等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Install Backbone

Backbone's only hard dependency is Underscore.js ( >= 1.4.3). For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include json2.js, and either jQuery ( >= 1.7.0) or Zepto.

If you want to started backbone ,you need loading Jquery first and Underscore.js second,then loading backbone.js 


 

Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. 


So for the purpose of the tutorial let's create a model. 

  Person = Backbone.Model.extend({

        initialize: function(){

            alert("Welcome to this world");

        }

    });

    

    var person = new Person;

So initialize() is triggered whenever you create a new instance of a model( models, collections and views work the same way ). You don't have to include it in your model declaration but you will find yourself using it more often than not.



Setting attributes(Pass parameters)

Now we want to pass some parameters when we create an instance of our model. 

   Person = Backbone.Model.extend({

        initialize: function(){

            alert("Welcome to this world");

        }

    });

    

    var person = new Person({ name: "Thomas", age: 67});

    // or we can set afterwards, these operations are equivelent

    var person = new Person();

    person.set({ name: "Thomas", age: 67});

     

So passing a JavaScript object to our constructor is the same as calling model.set(). Now that these models have attributes set we need to be able to retrieve them.



Getting attributes 

Using the model.get() method we can access model properties at anytime. 

 Person = Backbone.Model.extend({

        initialize: function(){

            alert("Welcome to this world");

        }

    });

    

    var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});

    

    var age = person.get("age"); // 67

    var name = person.get("name"); // "Thomas"

    var child = person.get("child"); // 'Ryan'


Setting model defaults

Sometimes you will want your model to contain default values. This can easily be accomplished by setting a property name 'defaults' in your model declaration.

 Person = Backbone.Model.extend({

        defaults: {

            name: 'Fetus',

            age: 0,

            child: ''

        },

        initialize: function(){

            alert("Welcome to this world");

        }

    });

    

    var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});

    

    var age = person.get("age"); // 67

    var name = person.get("name"); // "Thomas"

    var child = person.get("child"); // 'Ryan'

    


 Manipulating model attributes

Models can contain as many custom methods as you like to manipulate attributes. By default all methods are public. 

Person = Backbone.Model.extend({

        defaults: {

            name: 'Fetus',

            age: 0,

            child: ''

        },

        initialize: function(){

            alert("Welcome to this world");

        },

        adopt: function( newChildsName ){

            this.set({ child: newChildsName });

        }

    });

    

    var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});

    person.adopt('John Resig');

    var child = person.get("child"); // 'John Resig'

    

So we can implement methods to get/set and perform other calculations using attributes from our model at any time. 




Listening for changes to the model

Now onto one of the more useful parts of using a library such as backbone. All attributes of a model can have listeners bound to them to detect changes to their values. In our initialize function we are going to bind a function call everytime we change the value of our attribute. In this case if the name of our "person" changes we will alert their new name.

 Person = Backbone.Model.extend({

        defaults: {

            name: 'Fetus',

            age: 0

        },

        initialize: function(){

            alert("Welcome to this world");

            this.on("change:name", function(model){

                var name = model.get("name"); // 'Stewie Griffin'

                alert("Changed my name to " + name );

            });

        }

    });

    

    var person = new Person();

    person.set({name: 'Stewie Griffin'}); // This triggers a change and will alert()   

So we can bind the change listener to individual attributes or if we like simply 'this.on("change", function(model){});' to listen for changes to all attributes of the model. 


Interacting with the server 

Models are used to represent data from your server and actions you perform on them will be translated to RESTful operations.

The id attribute of a model identifies how to find it on the database usually mapping to the surrogate key.

For the purpose of this tutorial imagine that we have a mysql table called Users with the columns idnameemail.

The server has implemented a RESTful URL /user which allows us to interact with it.

Our model definition shall thus look like;

 var UserModel = Backbone.Model.extend({

        urlRoot: '/user',

        defaults: {

            name: '',

            email: ''

        }


    });


Creating a new model(Pass client data to server)

 If we wish to create a new user on the server then we will instantiate a new UserModel and call save. If the id attribute of the model is null, Backbone.js will send a POST request to the urlRoot of the server.

  var UserModel = Backbone.Model.extend({

        urlRoot: '/user',

        defaults: {

            name: '',

            email: ''

        }

    });

    var user = new Usermodel();

    // Notice that we haven't set an `id`

    var userDetails = {

        name: 'Thomas',

        email: 'thomasalwyndavis@gmail.com'

    };

    // Because we have not set a `id` the server will call

    // POST /user with a payload of {name:'Thomas', email: 'thomasalwyndavis@gmail.com'}

    // The server should save the data and return a response containing the new `id`

    user.save(userDetails, {

        success: function (user) {

            alert(user.toJSON());

        }

    })

注:在这里,如果我们后台的Server是php脚本,由于数据的类型是Content-Type:application/json 。 所以我们要得到POST过来的数据必须使用 PHP 数据流得到 $data = file_get_contents('php://input');




Getting a model(get data from server for restful) 

If we instantiate a model with an id, Backbone.js will automatically perform a get request to the urlRoot + '/id' (conforming to RESTful conventions).

 // Here we have set the `id` of the model

    var user = new Usermodel({id: 1});


    // The fetch below will perform GET /user/1

    // The server should return the id, name and email from the database

    user.fetch({

        success: function (user) {

            alert(user.toJSON());

        }

    })


Updating a model(for restful)

Now that we have a model that exist on the server we can perform an update using a PUT request. We will use the save api call which is intelligent and will send a PUT request instead of a POST request if an id is present(conforming to RESTful conventions)

  // Here we have set the `id` of the model

    var user = new Usermodel({

        id: 1,

        name: 'Thomas',

        email: 'thomasalwyndavis@gmail.com'

    });


    // Let's change the name and update the server

    // Because there is `id` present, Backbone.js will fire

    // PUT /user/1 with a payload of `{name: 'Davis', email: 'thomasalwyndavis@gmail.com'}`

    user.save({name: 'Davis'}, {

        success: function (model) {

            alert(user.toJSON());

        }

    });


Deleting a model(for restful)

When a model has an id we know that it exist on the server, so if we wish to remove it from the server we can call destroy. destroy will fire off a DELETE /user/id (conforming to RESTful conventions). 

    // Here we have set the `id` of the model

    var user = new Usermodel({

        id: 1,

        name: 'Thomas',

        email: 'thomasalwyndavis@gmail.com'

    });


    // Because there is `id` present, Backbone.js will fire

    // DELETE /user/1 

    user.destroy({

        success: function () {

            alert('Destroyed');

        }

    });



Tips and Tricks 

Get all the current attributes

     

    var person = new Person({ name: "Thomas", age: 67});

    var attributes = person.toJSON(); // { name: "Thomas", age: 67}

    /* This simply returns a copy of the current attributes. */

    

    var attributes = person.attributes;

    /* The line above gives a direct reference to the attributes and you should be careful when playing with it.   Best practise would suggest that you use .set() to edit attributes of a model to take advantage of backbone listeners. */  

Validate data before you set or save it

   Person = Backbone.Model.extend({

        // If you return a string from the validate function,

        // Backbone will throw an error

        validate: function( attributes ){

            if( attributes.age < 0 && attributes.name != "Dr Manhatten" ){

                return "You can't be negative years old";

            }

        },

        initialize: function(){

            alert("Welcome to this world");

            this.bind("error", function(model, error){

                // We have received an error, log it, alert it or forget it :)

                alert( error );

            });

        }

    });

    

    var person = new Person;

    person.set({ name: "Mary Poppins", age: -1 }); 

    // Will trigger an alert outputting the error

    

    var person = new Person;

    person.set({ name: "Dr Manhatten", age: -1 });

    // God have mercy on our souls

    





【基于QT的调色板】是一个使用Qt框架开发的色彩选择工具,类似于Windows操作系统中常见的颜色选取器。Qt是一个跨平台的应用程序开发框架,广泛应用于桌面、移动和嵌入式设备,支持C++和QML语言。这个调色板功能提供了横竖两种渐变模式,用户可以方便地选取所需的颜色值。 在Qt中,调色板(QPalette)是一个关键的类,用于管理应用程序的视觉样式。QPalette包含了一系列的颜色角色,如背景色、前景色、文本色、高亮色等,这些颜色可以根据用户的系统设置或应用程序的需求进行定制。通过自定义QPalette,开发者可以创建具有独特视觉风格的应用程序。 该调色板功能可能使用了QColorDialog,这是一个标准的Qt对话框,允许用户选择颜色。QColorDialog提供了一种简单的方式来获取用户的颜色选择,通常包括一个调色板界面,用户可以通过滑动或点击来选择RGB、HSV或其他色彩模型中的颜色。 横渐变取色可能通过QGradient实现,QGradient允许开发者创建线性或径向的色彩渐变。线性渐变(QLinearGradient)沿直线从一个点到另一个点过渡颜色,而径向渐变(QRadialGradient)则以圆心为中心向外扩散颜色。在调色板中,用户可能可以通过滑动条或鼠标拖动来改变渐变的位置,从而选取不同位置的颜色。 竖渐变取色则可能是通过调整QGradient的方向来实现的,将原本水平的渐变方向改为垂直。这种设计可以提供另一种方式来探索颜色空间,使得选取颜色更为直观和便捷。 在【colorpanelhsb】这个文件名中,我们可以推测这是与HSB(色相、饱和度、亮度)色彩模型相关的代码或资源。HSB模型是另一种常见且直观的颜色表示方式,与RGB或CMYK模型不同,它以人的感知为基础,更容易理解。在这个调色板中,用户可能可以通过调整H、S、B三个参数来选取所需的颜色。 基于QT的调色板是一个利用Qt框架和其提供的色彩管理工具,如QPalette、QColorDialog、QGradient等,构建的交互式颜色选择组件。它不仅提供了横竖渐变的色彩选取方式,还可能支持HSB色彩模型,使得用户在开发图形用户界面时能更加灵活和精准地控制色彩。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值