Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Backbone Bundle Laravel Package

devtime/backbone-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require devtime/backbone-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Devtime\BackboneBundle\DevtimeBackboneBundle::class => ['all' => true],
    ];
    
  2. Enable Backbone in Twig: In your base template (e.g., base.html.twig), include the bundle’s assets:

    {{ backbone_assets() }}
    

    This auto-loads jQuery, Underscore, and Backbone with default configurations.

  3. First Use Case: Create a simple Backbone model/view in a Twig template:

    <script type="text/javascript">
        $(document).ready(function() {
            var MyModel = Backbone.Model.extend({});
            var myModel = new MyModel({ name: 'Test' });
            console.log(myModel.get('name')); // Output: "Test"
        });
    </script>
    

Key Files to Review

  • Resources/public/js/: Default Backbone/Underscore/jQuery versions.
  • Resources/views/: Twig helpers (e.g., backbone_assets.html.twig).
  • DependencyInjection/DevtimeBackboneExtension.php: Configuration options.

Implementation Patterns

1. Asset Management

  • Custom Versions: Override default JS versions by copying files from vendor/devtime/backbone-bundle/Resources/public/js/ to web/js/ and updating backbone_assets() in Twig:

    {{ backbone_assets({
        jquery_version: '3.6.0',
        underscore_version: '1.13.1',
        backbone_version: '1.4.0'
    }) }}
    
  • Localization: Use Symfony’s asset pipeline (%kernel.debug%) to cache versions in production.

2. Twig Integration

  • Dynamic Loading: Load Backbone only on specific pages:

    {% if app.request.attributes.get('_route') == 'dashboard' %}
        {{ backbone_assets() }}
    {% endif %}
    
  • Custom Templates: Extend the bundle’s Twig functions by creating a custom template (e.g., templates/backbone/custom_assets.html.twig) and overriding the path in services.yaml:

    devtime_backbone:
        twig:
            template_path: 'templates/backbone/custom_assets.html.twig'
    

3. Backbone Configuration

  • Global Config: Pass Backbone settings via Symfony’s configuration:

    # config/packages/devtime_backbone.yaml
    devtime_backbone:
        backbone:
            debug: true
            url_root: '/api'
    

    Access in JavaScript:

    {{ backbone_config() }}
    <script>
        console.log(Backbone.config); // { debug: true, url_root: '/api' }
    </script>
    
  • Model/Collection Templates: Use Twig to render Backbone templates dynamically:

    {{ backbone_template('my_template', {
        item: myModel.toJSON()
    }) }}
    

4. API Integration

  • RESTful Routing: Combine with FOSRestBundle for Backbone model syncing:
    var MyModel = Backbone.Model.extend({
        urlRoot: '/api/my-resource', // Matches FOSRestBundle routes
        sync: function(method, model, options) {
            options.beforeSend = function(xhr) {
                xhr.setRequestHeader('X-Auth-Token', '{{ app.session.token }}');
            };
            return Backbone.sync.apply(this, arguments);
        }
    });
    

5. Modular Workflow

  • Separate JS Files: Organize Backbone code into modules (e.g., app/js/models/, app/js/views/) and load them via Twig:
    {{ backbone_assets() }}
    {{ include('backbone_js.html.twig') }}
    
    Where backbone_js.html.twig:
    {% block backbone_js %}
        <script src="{{ asset('js/models/my_model.js') }}"></script>
        <script src="{{ asset('js/views/my_view.js') }}"></script>
    {% endblock %}
    

Gotchas and Tips

Pitfalls

  1. Version Conflicts:

    • The bundle ships with specific versions of jQuery/Underscore/Backbone. If you use webpack-encore or other bundlers, ensure no version clashes occur. Explicitly set versions in backbone_assets() to avoid surprises.
  2. Twig Debug Mode:

    • In dev environment, Twig’s backbone_assets() may generate unminified files. For production, set debug: false in devtime_backbone config or use Symfony’s asset pipeline.
  3. CORS Issues:

    • If Backbone models sync with a non-Symfony API, ensure CORS headers are configured on the backend. Example for Symfony:
      # config/packages/nelmio_cors.yaml
      nelmio_cors:
          defaults:
              allow_origin: ['*']
              allow_methods: ['GET', 'POST', 'PUT', 'DELETE']
              allow_headers: ['*']
              expose_headers: ['*']
      
  4. Backbone Router Conflicts:

    • If using Symfony’s router (e.g., {{ path() }}) alongside Backbone routers, ensure routes don’t clash. Prefix Backbone routes with a namespace:
      var Router = Backbone.Router.extend({
          routes: {
              'app/dashboard': 'showDashboard'
          }
      });
      

Debugging Tips

  1. Check Asset Loading:

    • Verify assets are loaded by inspecting the <head> section. Missing files often indicate Twig template issues or incorrect paths.
  2. Backbone Console Errors:

    • Use Backbone.emulateJSON = true; if your API doesn’t send Content-Type: application/json headers. Add this via Twig:
      {{ backbone_config({
          emulate_json: true
      }) }}
      
  3. Symfony Profiler:

    • Enable the profiler (APP_DEBUG=true) to inspect Twig variables passed to backbone_assets() or backbone_config().

Extension Points

  1. Custom Build Process:

    • Override the default JS files by extending the bundle’s Resources/public/js/ directory. Use post-install scripts in composer.json to copy and minify files:
      {
          "scripts": {
              "post-install-cmd": [
                  "php bin/console assets:install",
                  "npm run build" // If using Webpack
              ]
          }
      }
      
  2. Event Dispatching:

    • Integrate with Symfony events (e.g., kernel.request) to dynamically inject Backbone data:
      // src/EventListener/BackboneListener.php
      public function onKernelRequest(GetResponseEvent $event) {
          $request = $event->getRequest();
          if ($request->attributes->get('_route') === 'dashboard') {
              $event->getRequest()->attributes->set('backbone_data', [
                  'user' => $this->getUserData()
              ]);
          }
      }
      
      Access in Twig:
      {{ backbone_config(app.request.attributes.backbone_data) }}
      
  3. Testing:

    • Use Symfony’s Panther or Nightwatch.js for Backbone-heavy UIs. Example Nightwatch test:
      module.exports = {
          'Backbone model test': function(browser) {
              browser
                  .url('/dashboard')
                  .waitForElementVisible('body')
                  .assert.containsText('body', 'Test'); // From Backbone model
          }
      };
      
  4. Laravel Migration Note:

    • While this bundle is for Symfony, similar patterns apply in Laravel:
      • Use Laravel Mix/Webpack for asset bundling.
      • Replace Twig helpers with Blade directives (e.g., @backboneAssets).
      • Leverage Laravel’s service container for Backbone configuration (e.g., config/backbone.php).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed