Table of Contents
Backbone Network Verification
Backbone.LayoutManager
Backbone.ModelBinder
结论
Home CMS Tutorial WordPress Enhance trunk with extensions to improve experience

Enhance trunk with extensions to improve experience

Aug 30, 2023 pm 07:29 PM

Enhance trunk with extensions to improve experience

Backbone is becoming increasingly popular as a web application development framework. With this popularity came countless extensions and plugins to enhance the functionality of the framework and fill in the holes that others felt needed to be filled. Let’s take a look at some of the best options.


Backbone.Puppet

Developed by Derick Bailey, this extension is quite large and is my personal favorite. Instead of adding a feature or two to Backbone, Derick decided to fill all of the biggest holes that he felt existed. Here’s what he said about it in the GitHub project’s readme.

"Backbone.Marionette is a composite application library for Backbone.js designed to simplify building large JavaScript applications. It is a collection of common design and implementation patterns discovered in applications I (Derick Bailey) have built using Backbone, and includes Various pieces inspired by composite application architecture, such as Microsoft's "Prism" framework."

Let’s take a closer look at what Marionette has to offer us:

  • Application: This is the central object through which everything in the application communicates. It provides a quick and easy way to set up the main view of the application, a central event hub through which every module in the application can communicate so that they are not dependent on each other, and provides Initializer for granular control over how your application starts.
  • Modules: A way to encapsulate module code and name these modules on a central application object.
  • View: The new view class to extend provides native methods for cleanup so you don't end up with memory leaks. It also contains rendering templates; for simple views, just specify the template and model and it will take care of the rest.
  • Collections/Composite Views: This is where the "Composite Application Library" comes into play. These two views allow you to easily create views that can handle the process of rendering all views in a collection, even nested hierarchies of collections and models, with very little effort.
  • Regions and Layouts: A region is an object that handles all the work of rendering, unrendering, and closing views at a specific location in the DOM. A layout is just a normal view with built-in areas for working with subviews.
  • AppRouter: A new type of router that can use a controller to handle the workload so that the router only contains the configuration of the route.
  • Events: Marionette extends from the Wreqr project to make Backbone's events more powerful and can be used to create large-scale event-based applications.

I've only scratched the surface of what Marionette can do. I definitely recommend going to GitHub and reading their documentation on the wiki.

Additionally, Andrew Burgess covers Marionette in his Tuts Premium Advanced Backbone Patterns and Techniques course.


Backbone Network Verification

Backbone.Validation is designed to fill a small subset of problems: namely model validation. Backbone has multiple validation extensions, but this one seems to have gained the most respect from the community.

In fact, instead of writing a validate method for the model, you can create a validation property for the model, which is an object specifying each property you wish to validate and Rules that validate each attribute of the list. You can also specify error messages for each property and pass in a custom function to validate individual properties. You can see an example below, modified from one of the examples on their website.

var SomeModel = Backbone.Model.extend({
    validation: {
        name: {
            required: true
        },
        'address.street': {
            required: true
        },
        'address.zip': {
            length: 4
        },
        age: {
            range: [1, 80]
        },
        email: {
            pattern: 'email',
            // supply your own error message
            msg: "Please enter a valid email address"
        },
        // custom validation function for `someAttribute`
        someAttribute: function(value) {
            if(value !== 'somevalue') {
                return 'Error message';
            }
        }
    }
});
Copy after login

There are countless built-in validators and schemas you can check, and there's even a way to extend the list with your own global validator. This Backbone plugin doesn’t make validation fun, but it does remove any excuse for not adding validation. Please visit their website for more examples and more in-depth instructions on how to use this wonderful tool.


Backbone.LayoutManager

Backbone.LayoutManager is to make Backbone’s views better. Like Backbone.Marionette, it introduces cleanup code to prevent memory leaks, handles all boilerplate, and leaves you with only configuration and application-specific code. Unlike Marionette, LayoutManager focuses specifically on views.

Because LayoutManager only focuses on views, it can do more for views than Marionette. For example, LayoutManager is able to perform asynchronous rendering when you want to dynamically load a template from an external file.

LayoutManager can also handle subviews, albeit in a very different way than Marionette. But either way, it's mostly configuration, which makes things very simple and eliminates 90% of the work you'd need to do if you were trying to implement it all yourself. Take a look at the following simple example of adding three subviews to a view:

Backbone.Layout.extend({
    views: {
      "header": new HeaderView(),
      "section": new ContentView(),
      "footer": new FooterView()
    }
});
Copy after login

像往常一样,请务必参阅 GitHub 页面和文档以了解更多信息。


Backbone.ModelBinder

Backbone.ModelBinder 在模型中的数据和视图显示的标记之间创建链接。您已经可以通过绑定到模型上的更改事件并再次渲染视图来完成此操作,但 ModelBinder 更高效且更易于使用。

看一下下面的代码:

var MyView = Backbone.View.extend({
    template: _.template(myTemplate),

    initialize: function() {
        // Old Backbone.js way
        this.model.on('change', this.render, this);
        // or the new Backbone 0.9.10+ way
        this.listenTo(this.model, 'change', this.render);
    },

    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
    }
});
Copy after login

这种方法的问题在于,每当更改单个属性时,我们都需要重新渲染整个视图。此外,在每次渲染时,我们都需要将模型转换为 JSON。最后,如果希望绑定是双向的(当模型更新时,DOM 也会更新,反之亦然),那么我们需要向视图添加更多逻辑。

此示例使用 Underscore 的 template 函数。让我们假设我们传递给它的模板如下所示:

<form action="...">
    <label for="firstName">First Name</label>
    <input type="text" id="firstName" name="firstName" value="<%= firstName %>">

    <label for="lastName">Last Name</label>
    <input type="text" id="lastName" name="lastName" value="<%= lastName %>">
</form>
Copy after login

使用标签 <%=%> 使 template 函数将这些区域替换为我们从模型发送的 JSON 中存在的 firstNamelastName 属性。我们假设该模型也具有这两个属性。

使用 ModelBinder,我们可以删除这些模板标签并以普通 HTML 形式发送。 ModelBinder 将查看 input 标记上的 name 属性的值,并自动将该属性的模型值分配给该标记的 value 属性。例如,第一个 inputname 设置为“firstName”。当我们使用 ModelBinder 时,它会看到这一点,然后将 inputvalue 设置为模型的 firstName 属性。

下面,您将看到我们之前的示例在切换到使用 ModelBinder 后的外观。另外,要意识到绑定是双向的,因此如果 input 标签更新,模型将自动为我们更新。

HTML 模板:

<form action="...">
    <label for="firstName">First Name</label>
    <input type="text" id="firstName" name="firstName">

    <label for="lastName">Last Name</label>
    <input type="text" id="lastName" name="lastName">
</form>
Copy after login

JavaScript 视图:

var MyView = Backbone.View.extend({
    template: myTemplate,

    initialize: function() {
        // No more binding in here
    },

    render: function() {
        // Throw the HTML right in
        this.$el.html(this.template);
        // Use ModelBinder to bind the model and view
        modelBinder.bind(this.model, this.el);
    }
});
Copy after login

现在我们有了干净的 HTML 模板,我们只需要一行代码就可以使用 modelBinder.bind 将视图的 HTML 和模型绑定在一起。 modelBinder.bind 采用两个必需参数和一个可选参数。第一个参数是将绑定到 DOM 的数据的模型。第二个是将递归遍历的 DOM 节点,搜索要进行的绑定。最后一个参数是 binding 对象,如果您不喜欢默认用法,它指定如何完成绑定的高级规则。

ModelBinder 不仅仅可以用于 input 标签。它适用于任何元素。如果元素是某种类型的表单输入,例如 inputselecttextarea,它将相应地更新这些元素的值。如果您绑定到一个元素,例如 divspan,它会将模型的数据放置在该元素的开始和结束标记之间(例如 <span name="firstName">[数据在此处] <span></span></span>)。

Backbone.ModelBinder 背后的功能比我在这里演示的要强大得多,因此请务必阅读 GitHub 存储库上的文档以了解所有相关信息。


结论

事情就这样结束了。我只介绍了少数扩展和插件,但这些是我认为最有用的。

Backbone 格局在不断变化。如果您想查看各种可用 Backbone 扩展的完整列表,请访问此 wiki 页面,Backbone 团队会定期更新该页面。

The above is the detailed content of Enhance trunk with extensions to improve experience. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

See all articles