Generic AssetBundle

Gentlemen,

I’m trying to implement a generic AssetBundle in order to register my assets dynamically(custom .js and .css that only one view uses). After overriding the constructor, and making the call in the view, I get the following error:

Invalid Configuration – yii\base\InvalidConfigException

Missing required parameter "js" when instantiating "app\assets\GenericAsset".

• 1. in C:\wamp\www\tiger\vendor\yiisoft\yii2\di\Container.php

Any help is greatly appreciated.

My class: GenericAsset.php

namespace app\assets;

use yii\web\AssetBundle;

class GenericAsset extends AssetBundle

{

public $basePath = '@webroot';


public $baseUrl = '@web';   


public $css = [];


public $jsOptions = ['position' => \yii\web\View::POS_HEAD];


public $js;


public $depends = [ ];

public function __construct($js, $config = []){

	$this->js = $js;	


    parent::__construct($config);


}	

}

View:projects.php

<?php

use app\assets\JqgridAsset;

use app\assets\GenericAsset;

use yii\web\View;

use app\assets\app\assets;

JqgridAsset::register($this);

$asset = new GenericAsset([‘js_views/project/projects.js’]);

$asset::register($this);

// Invoke function that was published in the asset

$this->registerJs(“render_projects();”, View::POS_LOAD, ‘my-options’);

?>

There’s no need to create a new class for that, yii\web\View::registerCssFile() and yii\web\View::registerJsFile() should do the job.

The problem with this code is that you call a static method on an instance and this method call results in an attempt to create a new instance of your AssetBundle class, without the required constructor parameter. As far as I know, there’s no way to register AssetBundle instances directly in yii\web\View because it uses yii\web\AssetManager as a factory for asset bundles (in order to make it possible to override asset bundle proprties from configuration file).

I did not want to use registerCssFile and RegisterJsFile because the resources would be published outside the Cashe Busting mechanism that AssetBundle provides and during the life cycle of the app, every time I update the js file the user would have to CTRL+F5 to get the latest version.

Another option would be to create an AssetBundle with the custom scripts for each view, but I was looking for a generic approach that would give me the benefits of AssetBundle without maintaining tens of separate classes and scripts.

thx for the input phtamas