0

我有一个 URL 路由,该路由有一个参数,其值在页面加载时提前未知。例如:

/读/书/页/:页

但是当用户在选择屏幕时,他们可以输入他们想要开始的页码,然后单击提交。是否可以捕获此表单提交并将其放置在 URL 中?通常有一个问号(?),因为它是一个 GET 请求。但是骨干网怎么能抓住呢?

4

1 回答 1

0

演示:

http://jsfiddle.net/vpetrychuk/PT2tU/

JS:

var Model = Backbone.Model.extend({
    url : function () {
        return 'http://fiddle.jshell.net/echo/json?page=' + this.get('page');
    },
    // remove it
    parse : function (response) {
        response || (response = {});
        response.justToTriggerChangeEvent = Math.random();
        return response;
    },
    getPageContent : function () {
        return 'Here should be page a content for page #' + this.get('page');
    }
});

var View = Backbone.View.extend({
    el : '[data-page]',
    events : {
        'submit' : 'submit'
    },
    initialize : function () {
        this.listenTo(this.model, 'change', this.showPage);
    },
    showPage : function () {
        this.$('[data-page-content]').html(this.model.getPageContent());
    },
    submit : function (e) {
        e.preventDefault();
        var page = this.$('[data-page-num]').val();
        if (page) {
            app.navigate('read/book/page/' + page, true);
        }
    }
});

var Router = Backbone.Router.extend({
    routes : {
        'read/book/page/:page' : 'page'
    },
    initialize : function (options) {
        this.bookModel = options.bookModel;
    },
    page : function (page) {
        this.bookModel.set('page', page);
        this.bookModel.fetch();
    }
});

var model = new Model();
var view = new View({model:model});
var app = new Router({bookModel:model});

Backbone.history.start();

HTML:

<div data-page>
    <form>
        <label><input type="text" data-page-num /></label>
        <button type="submit">Submit</button>
    </form>
    <div data-page-content></div>
</div>
于 2013-09-08T06:41:52.737 回答