2.View学习(Backbone Tutorials)

本文介绍Backbone.js视图的基础用法,包括初始化、设置DOM元素、加载模板及监听事件等关键步骤,并通过搜索框实例展示具体实现过程。

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

What is a view?

Backbone views are used to reflect what your applications' data models look like. They are also used to listen to events and react accordingly. This tutorial will not be addressing how to bind models and collections to views but will focus on view functionality and how to use views with a JavaScript templating library, specifically Underscore.js's _.template.

We will be using jQuery 1.8.2 as our DOM manipulator. It's possible to use other libraries such as MooTools or Sizzle, but official Backbone.js documentation endorses jQuery. Backbone.View events may not work with other libraries other than jQuery.

For the purposes of this demonstration, we will be implementing a search box. A live example can be found on jsFiddle.

  SearchView = Backbone.View.extend({

        initialize: function(){

            alert("Alerts suck.");

        }

    });


    // The initialize function is always called when instantiating a Backbone View.

    // Consider it the constructor of the class.

    var search_view = new SearchView();



The "el" property

The "el" property references the DOM object created in the browser. Every Backbone.js view has an "el" property, and if it not defined, Backbone.js will construct its own, which is an empty div element.

Let us set our view's "el" property to div#search_container, effectively making Backbone.View the owner of the DOM element.

<divid="search_container"></div>


<script type="text/javascript"]]>

    SearchView = Backbone.View.extend({

        initialize: function(){

            alert("Alerts suck.");

        }

    });

    

    var search_view = new SearchView({ el: $("#search_container") });

</script> 

Note: Keep in mind that this binds the container element. Any events we trigger must be in this element.


Loading a template

Backbone.js is dependent on Underscore.js, which includes its own micro-templating solution. Refer to Underscore.js's documentation for more information.

Let us implement a "render()" function and call it when the view is initialized. The "render()" function will load our template into the view's "el" property using jQuery.

<script type="text/template"id="search_template"]]>

  <label]]]]>Search</label>

  <input type="text" id="search_input"/>

  <input type="button" id="search_button" value="Search"/>

</script>


<divid="search_container"></div>


<script type="text/javascript"]]>

    SearchView = Backbone.View.extend({

        initialize: function(){

            this.render();

        },

        render: function(){

            // Compile the template using underscore

            var template= _.template( $("#search_template").html(), {} );

            // Load the compiled HTML into the Backbone "el"

            this.$el.html( template );

        }

    });

    

    var search_view = new SearchView({ el: $("#search_container") });

</script> 

Tip: Place all your templates in a file and serve them from a CDN. This ensures your users will always have your application cached.(注意一下加载顺序,必须先加载到template之后,我们才可以使用模板的加载)


Listening for events 

To attach a listener to our view, we use the "events" attribute of Backbone.View. Remember that event listeners can only be attached to child elements of the "el" property. Let us attach a "click" listener to our button.

<script type="text/template"id="search_template"]]]]>

  <label]]]]>Search</label>

  <input type="text" id="search_input"/>

  <input type="button" id="search_button" value="Search"/>

</script>


<divid="search_container"></div>


<script type="text/javascript"]]]]>

    SearchView = Backbone.View.extend({

        initialize: function(){

            this.render();

        },

        render: function(){

            var template= _.template( $("#search_template").html(), {} );

            this.$el.html( template );

        },

        events: {

            "click input[type=button]":"doSearch"

        },

        doSearch: function( event ){

            // Button clicked, you can access the element that was clicked with event.currentTarget

            alert( "Search for "+ $("#search_input").val() );

        }

    });


    var search_view = new SearchView({ el: $("#search_container") });

</script>


Tips and Tricks 

Using template variables

<script type="text/template"id="search_template"]]]]>

    <!-- Access template variableswith <%= %> -->

    <label><%= search_label%></label>

    <input type="text" id="search_input"/>

    <input type="button" id="search_button" value="Search"/>

</script>


<divid="search_container"></div>


<script type="text/javascript"]]]]>

     SearchView = Backbone.View.extend({

        initialize: function(){

            this.render();

        },

        render: function(){

            //Pass variables in using Underscore.js Template

            var variables= { search_label: "My Search" };

            // Compile the template using underscore

            var template= _.template( $("#search_template").html(), variables );

            // Load the compiled HTML into the Backbone "el"

            this.$el.html( template );

        },

        events: {

            "click input[type=button]":"doSearch"  

        },

        doSearch: function( event ){

            // Button clicked, you can access the element that was clicked with event.currentTarget

            alert( "Search for "+ $("#search_input").val() );

        }

    });

        

    var search_view = new SearchView({ el: $("#search_container") });

</script>

相关实例:

http://jsfiddle.net/thomas/C9wew/4/

http://jsfiddle.net/thomas/dKK9Y/6/

Traceback (most recent call last): [rank0]: File "/data3/workspace/chenzh/Face-SVD/train.py", line 1668, in <module> [rank0]: main(**OmegaConf.load(args.config)) [rank0]: File "/data3/workspace/chenzh/Face-SVD/train.py", line 1409, in main [rank0]: discr_fake_pred = attr_discriminator(vt_hat_latents) [rank0]: File "/data1/miniconda3/envs/face_svd/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl [rank0]: return self._call_impl(*args, **kwargs) [rank0]: File "/data1/miniconda3/envs/face_svd/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl [rank0]: return forward_call(*args, **kwargs) [rank0]: File "/data1/miniconda3/envs/face_svd/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 1632, in forward [rank0]: inputs, kwargs = self._pre_forward(*inputs, **kwargs) [rank0]: File "/data1/miniconda3/envs/face_svd/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 1523, in _pre_forward [rank0]: if torch.is_grad_enabled() and self.reducer._rebuild_buckets(): [rank0]: RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by passing the keyword argument `find_unused_parameters=True` to `torch.nn.parallel.DistributedDataParallel`, and by [rank0]: making sure all `forward` function outputs participate in calculating loss. [rank0]: If you already have done the above, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's `forward` function. Please include the loss function and the structure of the return value of `forward` of your module when reporting this issue (e.g. list, dict, iterable). [rank0]: Parameters which did not receive grad for rank 0: backbone.encoder_block3.0.norm.bias, backbone.encoder_block3.0.norm.weight, backbone.encoder_block3.0.conv.weight, backbone.encoder_block2.2.attn.to_out.0.bias, backbone.encoder_block2.2.attn.to_out.0.weight, backbone.encoder_block2.2.attn.to_v.weight, backbone.encoder_block2.2.attn.to_k.weight, backbone.encoder_block2.2.attn.to_q.weight, backbone.encoder_block2.2.norm.bias, backbone.encoder_block2.2.norm.weight, backbone.encoder_block2.2.resnet.conv2.bias, backbone.encoder_block2.2.resnet.conv2.weight, backbone.encoder_block2.2.resnet.norm2.bias, backbone.encoder_block2.2.resnet.norm2.weight, backbone.encoder_block2.2.resnet.conv1.bias, backbone.encoder_block2.2.resnet.conv1.weight, backbone.encoder_block2.2.resnet.norm1.bias, backbone.encoder_block2.2.resnet.norm1.weight, backbone.encoder_block2.1.attn.to_out.0.bias, backbone.encoder_block2.1.attn.to_out.0.weight, backbone.encoder_block2.1.attn.to_v.weight, backbone.encoder_block2.1.attn.to_k.weight, backbone.encoder_block2.1.attn.to_q.weight, backbone.encoder_block2.1.norm.bias, backbone.encoder_block2.1.norm.weight, backbone.encoder_block2.1.resnet.conv2.bias, backbone.encoder_block2.1.resnet.conv2.weight, backbone.encoder_block2.1.resnet.norm2.bias, backbone.encoder_block2.1.resnet.norm2.weight, backbone.encoder_block2.1.resnet.conv1.bias, backbone.encoder_block2.1.resnet.conv1.weight, backbone.encoder_block2.1.resnet.norm1.bias, backbone.encoder_block2.1.resnet.norm1.weight, backbone.encoder_block2.0.norm.bias, backbone.encoder_block2.0.norm.weight, backbone.encoder_block2.0.conv.weight, backbone.encoder_block1.1.attn.to_out.0.bias, backbone.encoder_block1.1.attn.to_out.0.weight, backbone.encoder_block1.1.attn.to_v.weight, backbone.encoder_block1.1.attn.to_k.weight, backbone.encoder_block1.1.attn.to_q.weight, backbone.encoder_block1.1.norm.bias, backbone.encoder_block1.1.norm.weight, backbone.encoder_block1.1.resnet.conv2.bias, backbone.encoder_block1.1.resnet.conv2.weight, backbone.encoder_block1.1.resnet.norm2.bias, backbone.encoder_block1.1.resnet.norm2.weight, backbone.encoder_block1.1.resnet.conv1.bias, backbone.encoder_block1.1.resnet.conv1.weight, backbone.encoder_block1.1.resnet.norm1.bias, backbone.encoder_block1.1.resnet.norm1.weight, backbone.encoder_block1.0.attn.to_out.0.bias, backbone.encoder_block1.0.attn.to_out.0.weight, backbone.encoder_block1.0.attn.to_v.weight, backbone.encoder_block1.0.attn.to_k.weight, backbone.encoder_block1.0.attn.to_q.weight, backbone.encoder_block1.0.norm.bias, backbone.encoder_block1.0.norm.weight, backbone.encoder_block1.0.resnet.conv2.bias, backbone.encoder_block1.0.resnet.conv2.weight, backbone.encoder_block1.0.resnet.norm2.bias, backbone.encoder_block1.0.resnet.norm2.weight, backbone.encoder_block1.0.resnet.conv1.bias, backbone.encoder_block1.0.resnet.conv1.weight, backbone.encoder_block1.0.resnet.norm1.bias, backbone.encoder_block1.0.resnet.norm1.weight, backbone.conv1x1.bias, backbone.conv1x1.weight [rank0]: Parameter indices which did not receive grad for rank 0: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
最新发布
05-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值